<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-08-01
 * @Time: 17:07
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Base.php
 */
namespace app\common\controller;

use app\common\model\ApiResponse;
use think\Controller;
use think\exception\HttpResponseException;
use think\Request;
use think\Validate;

/**
 * Class Base
 * @package app\common\controller
 *
 * @property string appId
 * @property string appSecret
 *
 * @property ClientAuth ca
 */
abstract class Base extends Controller
{

    protected $ca;

    public function __construct(Request $request=null)
    {
        parent::__construct($request);

        $this->ca = new ClientAuth();
        $this->ca->auth();

    }


    protected function isPC() {
        return $this->ca->isPC();
    }
    protected function isAPP() {
        return $this->ca->isAPP();
    }
    protected function isWECHAT() {
        return $this->ca->isWECHAT();
    }
    protected function iOSVerify() {
        $this->ca->iOSVerify();
    }

    /**
     * 处理post表单验证，
     * @param $validateRules
     * @return mixed
     * @throws HttpResponseException
     */
    protected function getAndCheckForm($validateRules) {
        $form = input('');
        $validate = new Validate($validateRules);
        if(!$validate->check($form)) {
            ApiResponse::error(ApiResponse::ERR_FORM_INVALID, $validate->getError());
        }
        return $form;
    }

    const LIMIT_DEFAULT = 10;
    /**
     * @param $form
     * @return array
     */
    protected static function pageFormat($form) {

        $page = intval($form['page'] ?? 1);
        if ($page <= 0) ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'page不能小于1');

        $rows = intval($form['rows'] ?? self::LIMIT_DEFAULT);
        return [
            'limit' => $rows,
            'offset' => intval(($page - 1) * $rows),
        ];
    }

    public function _empty() {
        ApiResponse::error(ApiResponse::ERR_INVALID_URI, '访问资源不存在');
    }
}